<template>
  <!-- 操作按钮区域 -->
  <el-button plain type="primary" style="margin-bottom: 10px;" @click="Open()">添加</el-button>
  <!-- 批量删除按钮：当没有选中项时禁用，防止用户误操作 -->
  <el-button type="danger" style="margin-bottom: 10px; margin-left: 10px;" @click="batchDelete"
    :disabled="multipleSelection.length === 0">
    批量删除
  </el-button>
  <el-button plain type="primary" style="float: right;" @click="Open()">导出</el-button>

  <!-- 数据表格：支持多选和批量操作 -->
  <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
    <!-- 选择列：用于批量操作的复选框 -->
    <el-table-column type="selection" width="55" />
    <el-table-column fixed type="index" label="序号" width="60" />
    <el-table-column prop="productionLineCode" label="产线编码" width="150" />
    <el-table-column prop="productionLineName" label="产线名称" width="150" />
    <el-table-column prop="workShopName" label="车间名称" width="180" />
    <el-table-column prop="productionLineDesc" label="产线描述" width="180" />
    <el-table-column prop="createrPeople" label="创建人" width="130" />
    <el-table-column prop="createTime" label="创建时间" width="180">
      <template #default="scope">
        {{ moment(scope.row.createTime).format('YYYY-MM-DD') }}
      </template>
    </el-table-column>
    <el-table-column prop="updateTime" label="修改时间" width="180">
      <template #default="scope">
        {{ moment(scope.row.updateTime).format('YYYY-MM-DD') }}
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link type="warning" @click="OpenUpdate(scope.row)">编辑</el-button>
        <el-button link type="danger" @click="Del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加车间弹窗 -->
  <el-dialog v-model="dialogVisible" title="添加产线" width="500px">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
      <el-form-item label="产线编码" prop="productionLineCode">
        <el-input v-model="ruleForm.productionLineCode" placeholder="请输入产线编码" />
      </el-form-item>
      <el-form-item label="产线名称" prop="productionLineName">
        <el-input v-model="ruleForm.productionLineName" placeholder="请输入产线名称" />
      </el-form-item>
      <el-form-item label="产线描述" prop="productionLineDesc">
        <el-input v-model="ruleForm.productionLineDesc" type="textarea" placeholder="请输入产线描述" />
      </el-form-item>
      <el-form-item label="所属车间" prop="workShopId">
        <el-select v-model="ruleForm.workShopId" placeholder="请选择车间">
          <el-option v-for="item in cj" :label="item.workShopName" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 修改车间弹窗 -->
  <el-dialog v-model="dialogVisibleUpdate" title="修改产线" width="500px">
    <el-form ref="ruleFormRef" :model="ruleFormUpdate" :rules="rules" label-width="120px">
      <el-form-item label="产线编码" prop="productionLineCode">
        <el-input v-model="ruleFormUpdate.productionLineCode" placeholder="请输入产线编码" />
      </el-form-item>
      <el-form-item label="产线名称" prop="productionLineName">
        <el-input v-model="ruleFormUpdate.productionLineName" placeholder="请输入产线名称" />
      </el-form-item>
      <el-form-item label="产线描述" prop="productionLineDesc">
        <el-input v-model="ruleFormUpdate.productionLineDesc" type="textarea" placeholder="请输入产线描述" />
      </el-form-item>
      <el-form-item label="所属车间" prop="workShopId">
        <el-select v-model="ruleFormUpdate.workShopId" placeholder="请选择车间">
          <el-option v-for="item in cj" :label="item.workShopName" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!--分页-->
  <div class="pagination-container">
    <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize" :page-sizes="[3, 6, 9, 12]"
      layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" class="custom-pagination" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import { fr, pa } from 'element-plus/es/locales.mjs';
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
import WorkShop from './WorkShop.vue';
const pinia = useCounterStore();
const tableData = ref([]) // 产线表格数据
const multipleSelection = ref<any[]>([]) // 存储用户选中的表格行数据，用于批量操作
const cj = ref([{ // 车间数据，用于产线关联车间的下拉选择
  "id": null,
  "workShopName": "",
}])
//产线向后端传参
const page = reactive({
  PageIndex: 1,
  PageSize: 5,
  totalcount: 0
})
//车间向后端传参
const pagecj = reactive({
  PageIndex: 1,
  PageSize: 100,
  totalcount: 0
})
//钩子
onMounted(() => {
  GetWorkShop()
  GetProductionLine()
})
//车间网络传出
const GetWorkShop = () => {
  axios.get('/api/FactoryModeling/GetWorkShop', { params: pagecj }).then(res => {
    if (res.data.code == 200) {
      cj.value = res.data.totalPage
      pagecj.totalcount = res.data.totalcount
    }
  })
}
//产线网络传输
const GetProductionLine = () => {
  axios.get('/api/FactoryModeling/GetProductionLine', { params: page }).then(res => {
    if (res.data.code == 200) {
      tableData.value = res.data.totalPage
      page.totalcount = res.data.totalcount
    }
  })
}
// 控制弹窗显示
const dialogVisible = ref(false);
const Open = () => {
  dialogVisible.value = true;
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "productionLineCode": "",
  "productionLineName": "",
  "workShopId": null,
  "productionLineDesc": "",
  "createrPeople": pinia.piniaDto.accountName
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  productionLineCode: [
    { required: true, message: '请输入产线编码', trigger: 'blur' },
  ],
  productionLineName: [
    {
      required: true,
      message: '请输入产线名称',
      trigger: 'blur',
    },
  ],
  workShopId: [
    {
      required: true,
      message: '请选择车间',
      trigger: 'blur',
    }],
  productionLineDesc: [
    {
      required: true,
      message: '请输入产线描述',
      trigger: 'blur',
    },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post('/api/FactoryModeling/AddProductionLine', ruleForm).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);

          dialogVisible.value = false;
          GetProductionLine(); // 提交成功后刷新表格数据
        } else {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  page.PageSize = val;
  GetProductionLine()
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  page.PageIndex = val;
  GetProductionLine()
}
const dialogVisibleUpdate = ref(false);
const OpenUpdate = (row: any) => {
  dialogVisibleUpdate.value = true
  ruleFormUpdate.id = row.id
  ruleFormUpdate.productionLineCode = row.productionLineCode
  ruleFormUpdate.productionLineName = row.productionLineName
  ruleFormUpdate.workShopId = row.workShopId
  ruleFormUpdate.productionLineDesc = row.productionLineDesc
}
const ruleFormUpdate = reactive({
  "id": null,
  "productionLineCode": "",
  "productionLineName": "",
  "workShopId": null,
  "productionLineDesc": "",
  "updaterPeople": pinia.piniaDto.accountName
})
//修改网络
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.put('/api/FactoryModeling/UpdateProductionLine', ruleFormUpdate).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
          dialogVisibleUpdate.value = false;
          GetProductionLine(); // 提交成功后刷新表格数据
        } else {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const Del = (id: any) => {
  ElMessageBox.confirm(
    '确定要删除该产线吗？删除后数据将无法恢复。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.post(`/api/FactoryModeling/DelProductionLine`, { id: id }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message);
          GetProductionLine(); // 删除成功后刷新表格数据
        } else {
          ElMessage.error(res.data.message);
        }
      }).catch(error => {
        ElMessage.error('删除失败，请重试');
        console.error('Delete error:', error);
      });
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
}

/**
 * 批量选择处理函数
 * 当用户在表格中选择/取消选择行时触发
 * @param val 当前选中的所有行数据数组
 */
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
}

/**
 * 批量删除功能
 * 删除用户选中的多条产线记录
 * 包含数据验证、用户确认、API调用、结果处理等完整流程
 */
const batchDelete = () => {
  // 1. 数据验证：检查是否有选中的数据
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }

  // 2. 提取选中行的ID数组，用于后端删除操作
  const ids = multipleSelection.value.map((item: any) => item.id);

  // 3. 显示确认对话框，防止用户误操作
  ElMessageBox.confirm(
    `确定要删除选中的 ${multipleSelection.value.length} 条产线记录吗？删除后数据将无法恢复。`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning', // 警告类型的对话框
    }
  )
    .then(() => {
      // 4. 用户确认删除，调用后端批量删除接口
      axios.post('/api/FactoryModeling/DelProductionLine', {
        id: 0,        // 单个删除时使用，批量删除时设为0
        ids: ids      // 要删除的ID数组
      }).then(res => {
        // 5. 处理删除结果
        if (res.data.code == 200) {
          // 删除成功
          ElMessage.success(res.data.message);
          GetProductionLine(); // 重新获取数据，刷新表格显示
          multipleSelection.value = []; // 清空选择状态，重置UI
        } else {
          // 删除失败，显示服务器返回的错误信息
          ElMessage.error(res.data.message);
        }
      }).catch(error => {
        // 6. 处理网络错误或其他异常
        ElMessage.error('批量删除失败，请重试');
        console.error('Batch delete error:', error);
      });
    })
    .catch(() => {
      // 7. 用户取消删除操作
      ElMessage.info('已取消批量删除');
    });
}
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.custom-pagination {
  --el-pagination-item-size: 32px;
  --el-pagination-item-bg: #ffffff;
  --el-pagination-item-color: #606266;
  --el-pagination-item-hover-color: #4096ff;
  --el-pagination-item-active-color: #ffffff;
  --el-pagination-item-active-bg: #4096ff;
  --el-pagination-border-radius: 6px;
  --el-pagination-margin: 0 5px;
}

.custom-pagination .el-pagination__prev,
.custom-pagination .el-pagination__next {
  width: 32px;
  height: 32px;
  border-radius: 6px;
}

.custom-pagination .el-pagination__sizes {
  margin-right: 10px;
}

.custom-pagination .el-pagination__total {
  margin-right: 10px;
  color: #606266;
}

.custom-pagination .el-pagination__item {
  margin: 0 5px;
  border-radius: 6px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.custom-pagination .el-pagination__item:hover {
  background-color: #f0f5ff;
}

.custom-pagination .el-pagination__item.is-active {
  background-color: #4096ff;
  color: #ffffff;
}
</style>
